const express = require('express')
const fs = require("fs")
const port = 3000

const app = express()

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    next();
});

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.post("/writed",(req,res)=>{
    var body = req.body;
    fs.readFile("./data/data.json",(err,data)=>{
        var list = JSON.parse(data)
        var istrue =  list.indexOf(body.url)!= -1
        if(!istrue){
            list.unshift(body.url)
            fs.writeFile("./data/data.json",JSON.stringify(list),((err,data)=>{
                if(!err){
                    res.send({
                        code:200,
                        msg:"链接保存成功"
                    })
                    var date = `./data/${new Date().toLocaleDateString().replace(new RegExp("/", "g"),".")}`

                    function newRead(){
                        fs.readFile(date,(err,datas)=>{
                            if(datas == undefined){
                                newWrite("")
                                //递归
                                newRead()
                                return
                            }
                            var newdata = datas.toString()
                            console.log(newdata)
                            newdata = (body.url + "," + newdata).replace(new RegExp(`"`,"g"),"")
                            newWrite(newdata)
                        })
                    }

                    newRead()
                    
                    function newWrite(data){
                        fs.writeFile(date,JSON.stringify(data),((err,data)=>{
                            console.log("保存成功")
                        }))
                    }
                }
            }))
            
        }else{
            res.status(201)
            res.send({
                code:201,
                msg:"有同名，保存失败"
            })
        }
    })
})

app.get("/Reader",(req,res)=>{
    var data = `./data/${new Date().toLocaleDateString().replace(new RegExp("/", "g"),".")}`
    fs.readFile(data,(err,data)=>{
        if(data != undefined){
            res.send({
                code:200,
                data:data.toString().replace(new RegExp("\""),"").replace(new RegExp("\""),"") 
            })
        }else{
            res.send({
                code:301,
                msg:"此文件暂无"
            })
        }
    })
    
})


app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})